<template>
  <div v-bind:id="id" v-bind:data="data"></div>
</template>

<script>
    export default {
        name: "barGraph",
        data() {
            return {
                ChartBarGraph: null,
            };
        },
        //  深度监听 父组件刚开始没有值，只有图标的配置项
        //  父组件ajax请求后改变数据的值，传递过来，图标已生成，监听传过来的值的改变
        // deep:true.深度监听，确保data中子项修改也能监听到。写法参考：https://cn.vuejs.org/v2/api/#watch
        watch: {
            data: {
                handler(newvalue, oldvalue) {
                    this.drawBarGraph(this.id, newvalue);
                },
                deep: true,
            },
        },
        props: ["id", "data", "clickOnOff", "params"],
        mounted() {
            this.drawBarGraph(this.id, this.data, this.clickOnOff, this.params);
        },
        methods: {
            drawBarGraph(id, data,clickOnOff,params) {
                let _this = this;
                let myChart = document.getElementById(id);
                this.ChartBarGraph = this.$echarts.init(myChart);
                this.ChartBarGraph.setOption(data);
                this.ChartBarGraph.dispatchAction({
                    type: "highlight",
                    seriesIndex: 0,
                    dataIndex: 0

                }); //设置默认选中高亮部分
                let me = this;
                this.ChartBarGraph.on('mouseover', function(e) {
                    //当检测到鼠标悬停事件，取消默认选中高亮
                    me.ChartBarGraph.dispatchAction({
                        type: 'downplay',
                        seriesIndex: 0,
                        dataIndex: 0
                    });
                    //高亮显示悬停的那块
                    me.ChartBarGraph.dispatchAction({
                        type: 'highlight',
                        seriesIndex: e.dataIndex,
                        dataIndex: e.dataIndex
                    });
                });

                //检测鼠标移出后显示之前默认高亮的那块
                this.ChartBarGraph.on('mouseout', function(e) {
                    me.ChartBarGraph.dispatchAction({
                        type: 'highlight',
                        seriesIndex: 0,
                        dataIndex: 0
                    });
                });
                // clickOnOff此属性的值为true或false
                if (clickOnOff) {
                    this.ChartBarGraph.on("click", function (param) {
                        alert("点击事件");
                        // 控制台打印数据的名称
                        // console.log(params.name);
                    });
                }
                window.addEventListener("resize", function () {
                    _this.ChartBarGraph.resize();
                });
            },
        },
        beforeDestroy() {
            if (this.ChartBarGraph) {
                this.ChartBarGraph.dispose();
            }
        },
    };
</script>

<style scoped>
</style>
